package samplebasic

import sweet.mvc.api._

/** Return fixed number of sample models for testing views. */
class QuickViewController(cxtRealPath: String) extends Controller{
  import sweet.helper._
  
  handle("/index"){
    HandlerNameView("ftlBasenames"->ftlBasenames)
  }
  
  handleReq("/source"){ req =>
    val basename = req("basename")
    val lines = new FileHelper(cxtRealPath+"/view/quickview/"+basename+".ftl").readLines
    HandlerNameView("lines"->lines, "basename"->basename)
  }
  
  /** Grab all file basenames from the view directory. */
  def ftlBasenames = {
    import sweet.helper.FileHelper._
    val dir = new java.io.File(cxtRealPath+"/view/quickview")
    val files = dir.listFiles.filter{ f=> f.isFile && f.getName.endsWith(".ftl") }
    files.map{ f => f.getBasename }
  }
  
  /** Have to override to all handlers to provide default models for testing. */
  override def findHandler(reqRoute: ReqRoute): Option[Handler] = {
    _handlers.get(reqRoute.handlerName) match {
      case Some(handler) => Some(handler)
      case None => {
        val handlerFunc = (req: Req, resp: Resp) => 
          View(reqRoute.handlerName, createModel+("basename"->reqRoute.handlerName.substring(1)))
        Some(handlerFunc)
      }
    }
  }
  
  /** A constant data model map for testing view. */
  def createModel = {
    val rBool = if(new java.util.Random().nextInt(2) == 1) true else false
    val names = List("Joe", "Fred", "Joe", "Susan")
    val item = Map("name"->"mouse", "price"->50.01)
    val customers = List(
      new Customer("Joe", "Smith",   JDate("1946-01-01"), 1002345),
      new Customer("Fred", "Smith",  JDate("1946-02-01"), 1002346),
      new Customer("Jack", "Smith",  JDate("1946-03-01"), 1002347),
      new Customer("Susan", "Smith", JDate("1946-04-01"), 1002348),
      new Customer("Mack", "Smith",  JDate("1946-05-01"), 1002349)
    )
    
    val model: Map[String, Any] = Map(
      "s" -> "Hello World",
      "i" -> 12345,
      "d" -> 9.878,
      "b" -> rBool,
      "dt" -> JDate.now,
      "names" -> names,
      "item" -> item,
      "file" -> new java.io.File("/tmp/test.txt"),
      "simple" -> new Simple(884),
      "customers" -> customers,
      "sysprops" -> System.getProperties
      )
    model
  }
  case class Simple(n: Int){ var num = n }
  case class Customer(first: String, last: String, bdt: JDate, account: Int)
}
